package com.epam.cdp.jpa.backingbeans;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import com.epam.cdp.jpa.dao.AuthorDAO;
import com.epam.cdp.jpa.model.Author;
import com.epam.cdp.jpa.model.Book;

@ManagedBean
@SessionScoped
public class AuthorsBackingBean implements Serializable {

    private static final long serialVersionUID = 1L;

    @EJB
    private transient AuthorDAO authorDAO;
    
    private Author newAuthor = new Author();
    private Author selectedAuthor;
    
    public List<Book> getAllBookFor(Author author) {
	return authorDAO.getAllBooksFor(author);
    }
    
    public List<Author> autocomplete(String query) {
	List<Author> result = new ArrayList<Author>();
	if (query != null && query.length() > 0) {
	    result.addAll(authorDAO.getByFirstNameFragment(query));
	}
	return result;
    }
    
    public void removeAuthor(Author detachedAuthor) {
	if(detachedAuthor != null) {
	    authorDAO.remove(detachedAuthor.getId());
	}
    }
    
    public List<Author> getAllAuthors(){
	return authorDAO.getAll();
    }
    
    public void addNewAuthor(){
	authorDAO.persist(newAuthor);
	newAuthor = new Author();
    }

    public void updateAuthorInfo() {
	if (selectedAuthor != null) {
	    authorDAO.update(selectedAuthor);
	}
    }
    
    public Author getNewAuthor() {
        return newAuthor;
    }

    public void setNewAuthor(Author newAuthor) {
        this.newAuthor = newAuthor;
    }

    public Author getSelectedAuthor() {
        return selectedAuthor;
    }

    public void setSelectedAuthor(Author selectedAuthor) {
        this.selectedAuthor = selectedAuthor;
    }
    
}
